package com.elvin.platform.udp;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 默认发送方式*/
@Log4j2
@Service
public class UdpSimpleClient {

  @Value("${udp.host}")
  private String udpHost;
  @Value("${udp.port}")
  private Integer udpPort;

  public void sendMessage(String message) {
    log.info("发送UDP: {}", message);
    InetSocketAddress inetSocketAddress = new InetSocketAddress(udpHost, udpPort);
    byte[] udpMessage = message.getBytes();
    DatagramPacket datagramPacket = null;
    try (DatagramSocket datagramSocket = new DatagramSocket()) {
      datagramPacket = new DatagramPacket(udpMessage, udpMessage.length, inetSocketAddress);
      datagramSocket.send(datagramPacket);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    }
    log.info("发送成功");
  }


  public static void main(String[] args) {
    String message = "fedc010f2c1c56f0ba000000030300040000049000";
    InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 6001);
    byte[] udpMessage = message.getBytes();
    DatagramPacket datagramPacket = null;
    try (DatagramSocket datagramSocket = new DatagramSocket()) {
      datagramPacket = new DatagramPacket(udpMessage, udpMessage.length, inetSocketAddress);
      datagramSocket.send(datagramPacket);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    }
    log.info("发送成功");
  }
}
